from datetime import datetime
import io
import re
from typing import List
import uuid
import PyPDF2
import pdfplumber
import requests
from io import BytesIO
import os
import fitz
from flask import json
import requests
from yida_app_service.chengxiang.yida_config import YidaClient
from oss_service.views import bucket


def merge_pdfs(paths, output):
    pdf_writer = PyPDF2.PdfWriter()

    for path in paths:
        pdf_reader = PyPDF2.PdfReader(path)
        for page in range(len(pdf_reader.pages)):
            # 将每页添加到写入器对象中
            pdf_writer.add_page(pdf_reader.pages[page])

    # 写入合并的 PDF 到文件
    with open(output, 'wb') as out:
        pdf_writer.write(out)

def merge_pdfs_from_memory(files: List[io.BytesIO], output: io.BytesIO):
    pdf_writer = PyPDF2.PdfWriter()
    for file in files:
        pdf_reader = PyPDF2.PdfReader(file)
        for page in range(len(pdf_reader.pages)):
            pdf_writer.add_page(pdf_reader.pages[page])
    pdf_writer.write(output)
def download_file_bytes(url: str) -> io.BytesIO:
    response = requests.get(url)
    if response.status_code == 200:
        return io.BytesIO(response.content)
    else:
        raise Exception(f"从下载链接：{url},下载文件失败")

def get_report_code_inpdf(pdf_content):
    with pdfplumber.open(pdf_content) as pdf:
        report_code = None
        for page in pdf.pages:
            text = page.extract_text()
            if text:
                lines = text.splitlines()
                if len(lines) >= 2:
                    if lines[0].startswith("报告编号"):
                        line = lines[0]
                    else:
                        line = lines[1]
                    parts = re.split("：|:", line)
                    if len(parts) > 1:
                        report_number = parts[1]
                        if report_code is None:
                            report_code = report_number
                        else:
                            if report_code == report_number:
                                continue
                            else:
                                return "error"
            print(f"report_code in pdf >>>>>>{report_code}")
        return report_code


def num_to_rmb(number):
    """金额转汉字"""
    # 汉字金额数字
    rmb_nums = "零壹贰叁肆伍陆柒捌玖"
    # 单位，这里的单位应对应实际的数位
    units = ["元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿"]
    # 转换成字符串，确保有小数点
    num_str = f"{float(number):.2f}"
    # 分割整数和小数部分
    integer, fraction = num_str.split(".")
    # 处理负数标志
    negative = "负" if integer.startswith("-") else ""
    integer = integer.replace("-", "")

    # 数字转大写汉字金额，整数部分
    if int(integer):
        rmb = ''.join([rmb_nums[int(num)] + (units[len(integer) - idx - 1] if num != '0' else '零') for idx, num in enumerate(integer)])
        # 合并连续的零
        rmb = rmb.replace('零零', '零')
        # 处理以零结尾的情况
        rmb = rmb.rstrip('零') + '元'
    else:
        rmb = "零元"

    # 处理小数部分
    jiao, fen = int(fraction[0]), int(fraction[1])
    if jiao == 0 and fen == 0:
        rmb += "整"
    else:
        rmb += (rmb_nums[jiao] + "角" if jiao else "零")
        rmb += (rmb_nums[fen] + "分" if fen else "")

    return negative + rmb

def fake_sign(report_path,participants_personal):
    '''伪签署'''
    yida_client = YidaClient()
    pdf_key = f"{report_path}/whole.pdf"
    pdf_content = bucket.get_object(pdf_key).read()
    pdf_io = BytesIO(pdf_content)
    pdf_document = fitz.open(stream=pdf_io, filetype="pdf")
    for participant in participants_personal:
        coor_str = participant.get("coordinate")
        try:
            coordinates = json.loads(coor_str)
        except Exception as e:
            coor_str = re.sub(r'(\w+):', r'"\1":', coor_str)
            coordinates = json.loads(coor_str)
        dingtalkUserId = participant.get("dingtalkUserId")
        seal_path = f"yida_app_service/chengxiang/resorce/seal/{dingtalkUserId}.png"
        if not os.path.exists(seal_path):
            person_info = yida_client.get_form_data_by_search_field("FORM-861F9E6F4AAE4D73A255247BF7991765XAKG",
                                                      yida_client.admin_user_id,
                                                      [
                                                          {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp0zbal4",
                                                            "value": dingtalkUserId
                                                          }
                                                      ])
            if person_info:
                seal_url = person_info[0].form_data.get("digitalSignatureField_lp0tv65b")
                if seal_url:
                    seal_content = requests.get(seal_url).content
                    with open(seal_path, "wb") as f:
                        f.write(seal_content)
        for coordinate in coordinates:
            lbx, lby, rtx, rty, page_num = coordinate['lbx'], coordinate['lby'], coordinate['rtx'], coordinate['rty'], coordinate['page']
            page = pdf_document[page_num - 1]
            page_height = page.rect.height
            lby = page_height - lby
            rty = page_height - rty
            page.insert_image(fitz.Rect(lbx, rty, rtx, lby), filename=seal_path)
    output_pdf_io = BytesIO()
    pdf_document.save(output_pdf_io)
    pdf_document.close()
    output_pdf_io.seek(0)
    fake_sign_pdf_key = f"file_tmp/{datetime.now().strftime('%Y%m%d')}/{uuid.uuid4()}.pdf"
    print("正在上传",fake_sign_pdf_key)
    bucket.put_object(fake_sign_pdf_key, output_pdf_io)
    return fake_sign_pdf_key